# -*- coding: utf-8 -*-
import os
from django import template
from django.http import Http404, HttpResponse
from django.core.paginator import Paginator
from django.template import RequestContext
from django.template.loaders.filesystem import load_template_source
from django.shortcuts import render_to_response, get_object_or_404
from django.contrib.sessions.models import Session
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.admin.models import LogEntry, ADDITION, CHANGE, DELETION
from hyperlog.decorators import superuser_or_404
from hyperlog.loader import render_local_template_to_response

# Monkeypatching
def logentry_action_desc(self):
    return {
        ADDITION:"Addition",
        CHANGE: "Change",
        DELETION: "Deletion"}.get(self.action_flag, self.action_flag)
LogEntry.hyperlog_action_flag = logentry_action_desc

def session_get_user(self):
    dec = self.get_decoded()
    user_id = dec.get('_auth_user_id', '')
    if not user_id:
        return "Anonymous"
    else:
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist: #@UndefinedVariable
            return "User not found (user_id=%d)" % user_id
Session.hyperlog_get_user = session_get_user

@superuser_or_404
def index(request):
    return render_local_template_to_response(request, 'index.html')

@superuser_or_404
def show_sessions(request, session_id=None):
    if session_id:
        session = get_object_or_404(Session, session_key=session_id)
        dec = session.get_decoded()
        user = session.hyperlog_get_user()
        return render_local_template_to_response(request, 'show_single_session.html', {
            "user": user,
            "session_key": session_id,
            "session_date": session.expire_date,
            "session_items": sorted(dec.items()),
            })
    sessions_list = Session.objects.order_by('-expire_date')
    paginator = Paginator(sessions_list, 50) # Show 25 contacts per page
    # Make sure page request is an int. If not, deliver first page.
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1
    # If page request (9999) is out of range, deliver last page of results.
    try:
        sessions = paginator.page(page)
    except (EmptyPage, InvalidPage): #@UndefinedVariable
        sessions = paginator.page(paginator.num_pages)
    return render_local_template_to_response(request, 'show_sessions.html', {
        "sessions": sessions })

@superuser_or_404
def show_admin_log(request, user_id=None, contenttype_id=None, object_id=None):
    actions_list = LogEntry.objects.order_by('-action_time')
    user = contenttype = None
    if user_id:
        user = get_object_or_404(User, pk=user_id)
        actions_list = actions_list.filter(user__pk=user_id)
    elif contenttype_id:
        contenttype = get_object_or_404(ContentType, pk=contenttype_id)
        actions_list = actions_list.filter(content_type__pk=contenttype_id)
    paginator = Paginator(actions_list, 50) # Show 25 contacts per page
    # Make sure page request is an int. If not, deliver first page.
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1
    # If page request (9999) is out of range, deliver last page of results.
    try:
        actions = paginator.page(page)
    except (EmptyPage, InvalidPage): #@UndefinedVariable
        actions = paginator.page(paginator.num_pages)
    link = ''
    if user:
        link = '../'
    elif contenttype:
        link = '../../'
    return render_local_template_to_response(request, 'show_admin_log.html', {
        "link": link,
        "contenttype": contenttype,
        "actions": actions })
